"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 服务流程
"""
from fastapi import APIRouter, Request, Query

from config import Config
from project.core.function import json_response
from project.lib.decorator import api_common, exec_duration
from project.model.database.basic import NodeType, Component
from project.model.database.cariabot import Activation
from project.model.basic import InformEntrance, RoleType, ProcessType, SmsTemplate, TelTemplate, InformType
from project.model.database.node import Node
from project.model.database.agent import Agent
from project.service.node import NodeService
from project.model.basic import FlushFrequency


common_router = APIRouter(prefix='/common', tags=['common'])


@common_router.get('/node_type/list', summary='节点类型列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_node_type_list(request: Request, session=None):
    """
    **desc**: 节点类型列表

    **url**: http(s)://{0}.udicaria.com/common/node_type/list

    **method**: POST

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    data = await NodeType.fetch_all(session, orders=(NodeType.rank,))

    return json_response(data=[v.dict() for v in data])


@common_router.get('/component/list', summary='页面组件列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_component_list(request: Request, session=None):
    """
    **desc**: 页面组件列表

    **url**: http(s)://{0}.udicaria.com/common/component/list

    **method**: POST

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    data = await Component.fetch_all(session, orders=(Component.rank,))

    return json_response(data=[v.dict() for v in data])


@common_router.get('/inform_entrance/list', summary='通知入口列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_inform_entrance_list(request: Request, session=None):
    """
    **desc**: 通知入口列表

    **url**: http(s)://{0}.udicaria.com/common/inform_entrance/list

    **method**: POST

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """

    return json_response(data=InformEntrance.list())


@common_router.get('/node/list', summary='节点列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_node_list(request: Request, flow_id: int = Query(..., title='服务流程id'), session=None):
    """
    **desc**: 节点列表

    **url**: http(s)://{0}.udicaria.com/common/node/list

    **method**: GET

    **params**:

        <query>:
            flow_id: 服务流程id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    code: 节点编号
                    name: 节点名称
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    nodes = await Node.fetch_all(session, wheres=(Node.flow_id == flow_id, ~Node.is_deleted))
    nodes = NodeService.sorted_nodes(nodes)

    items = [{'code': node.code, 'name': f'n{idx+1}-{node.name if node.name else "未知"}'} for idx, node in enumerate(nodes)]
    # 固定人工服务
    items.append({'code': 'S99999', 'name': f'n{len(nodes)+1}-人工服务'})

    return json_response(data=items)


@common_router.get('/activation_code/list', summary='激活码列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_activation_code_list(request: Request, session=None):
    """
    **desc**: 激活码列表

    **url**: http(s)://{0}.udicaria.com/common/activation_code/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    code: 激活码
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    data = await Activation.fetch_all(session)

    return json_response(data=[v.dict() for v in data])


@common_router.get('/external_url', summary='外部使用url')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_external_url(request: Request, session=None):
    """
    **desc**: 取得外部链接url

    **url**: http(s)://{0}.udicaria.com/common/external_url

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                url: 链接地址
            }
            exec_time: 接口后端处理时长
        }
    """
    return json_response(data={'url': Config.EXTERNAL_URL})


@common_router.get('/role_type/list', summary='角色类型列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_role_type_list(request: Request):
    """
    **desc**: 角色类型列表

    **url**: http(s)://{0}.udicaria.com/common/role_type/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """

    return json_response(data=RoleType.list())


@common_router.get('/process_type/list', summary='流程状态列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_process_node_list(request: Request):
    """
    **desc**: 流程状态列表

    **url**: http(s)://{0}.udicaria.com/common/process_type/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:[
                {
                    code: 流程顺序
                    value: 状态名称
                }
            ]
            exec_time: 接口后端处理时长
        }
    """

    return json_response(data=ProcessType.list())


@common_router.get('/sms_template/list', summary='短信模版列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_sms_template_list(request: Request):
    """
    **desc**: 短信模版列表

    **url**: http(s)://{0}.udicaria.com/common/sms_template/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:[
                {
                    code: 短信code
                    value: 短信名称
                    role_type: 角色类型 user/worker
                    content: 短信模版内容
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    return json_response(data=SmsTemplate.list())


@common_router.get('/tel_template/list', summary='电话通知模版列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_tel_template_list(request: Request):
    """
    **desc**: 电话通知模版列表

    **url**: http(s)://{0}.udicaria.com/common/tel_template/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:[
                {
                    code: 模版ID
                    value: 模版名称
                    role_type: 角色类型 user/worker
                    content: 短信模版内容
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    return json_response(data=TelTemplate.list())


@common_router.get('/inform_type/list', summary='通知类型列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_inform_type_list(request: Request):
    """
    **desc**: 通知类型列表

    **url**: http(s)://{0}.udicaria.com/common/inform_type/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    return json_response(data=InformType.list())


@common_router.get('/flush_frequency/list', summary='更新频率列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_flush_frequency_list(request: Request):
    """
    **desc**: 更新频率列表

    **url**: http(s)://{0}.udicaria.com/common/flush_frequency/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:[
                {
                    code: 更新频率code
                    value: 更新频率名称
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    return json_response(data=FlushFrequency.list())


@common_router.get('/agent/list', summary='agent列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_agent_list(request: Request, organization_code: str = Query('', title='机构编号'), session=None):
    """
    **desc**: agent列表

    **url**: http(s)://{0}.udicaria.com/common/agent/list

    **method**: GET

    **params**:

        <query>:
            organization_code: 机构编号

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                code: 智能体编号
                title: 智能体标题
                is_default: 是否默认
            }
            exec_time: 接口后端处理时长
        }
    """
    wheres = list()
    if organization_code:
        wheres.append(Agent.organization_code == organization_code)
    wheres.append(~Agent.is_deleted)
    data = await Agent.fetch_all(session, wheres=wheres, orders=(Agent.organization_code, Agent.id.desc()))
    items = [v.dict('code', 'title', 'is_default') for v in data]

    return json_response(data=items)
